package controllers

import play.mvc.Controller
import dao.{MessageDAO, UserDAO}


object SecureREST extends Controller with Secure {
  import views.Rest._
  import config.Services._
  
  def message(id:Int) = {
    using(dbSession){ s =>
      MessageDAO.findByID(id) match {
        case Some(msg)   =>
          {
            if(msg.destination.name == session("username").get){ //XXX: Extra verifications
              html.message(msg)
            } else {
              //Forbidden
              Application.login
            }
          }
        case None => <div class="NotFound" />
      }
    }
  }
  
  def userByName (username:String, format:String) = {
    using(dbSession){ s =>
      val u = UserDAO.findByName(username) 
      outputUser(u, format)
    }
  }
  
  def user(id:Int, format:String) = {
    using(dbSession){ s =>
      val u = UserDAO.findById(id)
      outputUser(u, format)
    }
  }
  
  private def outputUser(u:Option[models.User], format:String) = {
    if(format == "htm"){
      Html( u map { html user (_, session("username") ) }  getOrElse ( <div>Perfil no encontrado</div> ) )
    } else if(format == "xml"){
      Xml( u.map( html userXML _ ).getOrElse("""<?xml version="1.0" encoding="utf-8"?><user />""") )
    }
  }

}
